<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>4 数据库与身份认证 | HasakWebBlog</title>
    <meta name="generator" content="VuePress 1.9.7">
    <link rel="icon" href="/favicon.ico">
    <meta name="description" content="hasak">
    <meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
    
    <link rel="preload" href="/assets/css/0.styles.a5a0d673.css" as="style"><link rel="preload" href="/assets/js/app.c7915c77.js" as="script"><link rel="preload" href="/assets/js/3.f80332a6.js" as="script"><link rel="preload" href="/assets/js/1.5cffa4a1.js" as="script"><link rel="preload" href="/assets/js/47.994c7d71.js" as="script"><link rel="prefetch" href="/assets/js/10.02ae8499.js"><link rel="prefetch" href="/assets/js/11.c5238d8f.js"><link rel="prefetch" href="/assets/js/12.be21fd80.js"><link rel="prefetch" href="/assets/js/13.bd684308.js"><link rel="prefetch" href="/assets/js/14.b5f9fc77.js"><link rel="prefetch" href="/assets/js/15.318683dc.js"><link rel="prefetch" href="/assets/js/16.74f9d94e.js"><link rel="prefetch" href="/assets/js/17.cd1e6d69.js"><link rel="prefetch" href="/assets/js/18.901e5492.js"><link rel="prefetch" href="/assets/js/19.417d2070.js"><link rel="prefetch" href="/assets/js/20.39ec66a2.js"><link rel="prefetch" href="/assets/js/21.fbf1aaf8.js"><link rel="prefetch" href="/assets/js/22.736aeb98.js"><link rel="prefetch" href="/assets/js/23.abcdc310.js"><link rel="prefetch" href="/assets/js/24.26658596.js"><link rel="prefetch" href="/assets/js/25.40bdc691.js"><link rel="prefetch" href="/assets/js/26.29ac009b.js"><link rel="prefetch" href="/assets/js/27.edc6afbf.js"><link rel="prefetch" href="/assets/js/28.b9c1065e.js"><link rel="prefetch" href="/assets/js/29.b46f8f9e.js"><link rel="prefetch" href="/assets/js/30.6839ae7e.js"><link rel="prefetch" href="/assets/js/31.85913f4e.js"><link rel="prefetch" href="/assets/js/32.098b21df.js"><link rel="prefetch" href="/assets/js/33.faced894.js"><link rel="prefetch" href="/assets/js/34.239b19e7.js"><link rel="prefetch" href="/assets/js/35.5c8a8406.js"><link rel="prefetch" href="/assets/js/36.46f0ebac.js"><link rel="prefetch" href="/assets/js/37.2456f410.js"><link rel="prefetch" href="/assets/js/38.b76624ee.js"><link rel="prefetch" href="/assets/js/39.64ecef14.js"><link rel="prefetch" href="/assets/js/4.7d7a493e.js"><link rel="prefetch" href="/assets/js/40.a1304a44.js"><link rel="prefetch" href="/assets/js/41.f98208ce.js"><link rel="prefetch" href="/assets/js/42.f0be4a4c.js"><link rel="prefetch" href="/assets/js/43.1a46f61e.js"><link rel="prefetch" href="/assets/js/44.d579b00f.js"><link rel="prefetch" href="/assets/js/45.8e8ea47a.js"><link rel="prefetch" href="/assets/js/46.1b194721.js"><link rel="prefetch" href="/assets/js/48.f17a641c.js"><link rel="prefetch" href="/assets/js/49.0d9ea06f.js"><link rel="prefetch" href="/assets/js/5.176296fc.js"><link rel="prefetch" href="/assets/js/50.e36885a9.js"><link rel="prefetch" href="/assets/js/51.64538ee2.js"><link rel="prefetch" href="/assets/js/52.1fd24c2e.js"><link rel="prefetch" href="/assets/js/53.967b1458.js"><link rel="prefetch" href="/assets/js/54.05b15a98.js"><link rel="prefetch" href="/assets/js/55.3c78b9d4.js"><link rel="prefetch" href="/assets/js/56.8d130c30.js"><link rel="prefetch" href="/assets/js/57.0008c022.js"><link rel="prefetch" href="/assets/js/58.4b49a382.js"><link rel="prefetch" href="/assets/js/59.8bb182dc.js"><link rel="prefetch" href="/assets/js/6.90835ce9.js"><link rel="prefetch" href="/assets/js/60.93235335.js"><link rel="prefetch" href="/assets/js/61.78370acd.js"><link rel="prefetch" href="/assets/js/62.1144f314.js"><link rel="prefetch" href="/assets/js/63.7fb72cd2.js"><link rel="prefetch" href="/assets/js/64.de8ba1be.js"><link rel="prefetch" href="/assets/js/65.cefa274d.js"><link rel="prefetch" href="/assets/js/66.32ad44bf.js"><link rel="prefetch" href="/assets/js/67.558c356c.js"><link rel="prefetch" href="/assets/js/68.15a3af19.js"><link rel="prefetch" href="/assets/js/69.b1b26c0a.js"><link rel="prefetch" href="/assets/js/7.2c075495.js"><link rel="prefetch" href="/assets/js/70.cb9b8e94.js"><link rel="prefetch" href="/assets/js/71.e371986a.js"><link rel="prefetch" href="/assets/js/72.a8af9117.js"><link rel="prefetch" href="/assets/js/73.dcc5a1af.js"><link rel="prefetch" href="/assets/js/74.803a909b.js"><link rel="prefetch" href="/assets/js/75.8129f8f6.js"><link rel="prefetch" href="/assets/js/76.ffcb07fc.js"><link rel="prefetch" href="/assets/js/8.9b4cfefe.js"><link rel="prefetch" href="/assets/js/9.e529cf11.js">
    <link rel="stylesheet" href="/assets/css/0.styles.a5a0d673.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container no-sidebar" data-v-7dd95ae2><div data-v-7dd95ae2><div class="password-shadow password-wrapper-out" style="display:none;" data-v-59e6cb88 data-v-7dd95ae2 data-v-7dd95ae2><h3 class="title" data-v-59e6cb88>HasakWebBlog</h3> <p class="description" data-v-59e6cb88>hasak</p> <label id="box" class="inputBox" data-v-59e6cb88><input type="password" value="" data-v-59e6cb88> <span data-v-59e6cb88>Konck! Knock!</span> <button data-v-59e6cb88>OK</button></label> <div class="footer" data-v-59e6cb88><span data-v-59e6cb88><i class="iconfont reco-theme" data-v-59e6cb88></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-59e6cb88>vuePress-theme-reco</a></span> <span data-v-59e6cb88><i class="iconfont reco-copyright" data-v-59e6cb88></i> <a data-v-59e6cb88><span data-v-59e6cb88>hasak</span>
          
        <span data-v-59e6cb88>2022 - </span>
        2023
      </a></span></div></div> <div class="hide" data-v-7dd95ae2><header class="navbar" data-v-7dd95ae2><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/" class="home-link router-link-active"><img src="/logo.png" alt="HasakWebBlog" class="logo"> <span class="site-name">HasakWebBlog</span></a> <div class="links"><div class="color-picker"><a class="color-button"><i class="iconfont reco-color"></i></a> <div class="color-picker-menu" style="display:none;"><div class="mode-options"><h4 class="title">Choose mode</h4> <ul class="color-mode-options"><li class="dark">dark</li><li class="auto active">auto</li><li class="light">light</li></ul></div></div></div> <div class="search-box"><i class="iconfont reco-search"></i> <input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  Home
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      前端学习
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/HTML5&amp;CSS3/" class="nav-link"><i class="undefined"></i>
  HTML5&amp;CSS3
</a></li><li class="dropdown-item"><!----> <a href="/categories/Javascript/" class="nav-link"><i class="undefined"></i>
  Javascript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Node/" class="nav-link"><i class="undefined"></i>
  Node
</a></li><li class="dropdown-item"><!----> <a href="/categories/VUE/" class="nav-link"><i class="undefined"></i>
  VUE
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tags
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系我
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://github.com/hasakxu" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav></div></header> <div class="sidebar-mask" data-v-7dd95ae2></div> <aside class="sidebar" data-v-7dd95ae2><div class="personal-info-wrapper" data-v-1fad0c41 data-v-7dd95ae2><img src="/dog.png" alt="author-avatar" class="personal-img" data-v-1fad0c41> <h3 class="name" data-v-1fad0c41>
    hasak
  </h3> <div class="num" data-v-1fad0c41><div data-v-1fad0c41><h3 data-v-1fad0c41>66</h3> <h6 data-v-1fad0c41>Articles</h6></div> <div data-v-1fad0c41><h3 data-v-1fad0c41>5</h3> <h6 data-v-1fad0c41>Tags</h6></div></div> <ul class="social-links" data-v-1fad0c41></ul> <hr data-v-1fad0c41></div> <nav class="nav-links"><div class="nav-item"><a href="/" class="nav-link"><i class="iconfont reco-home"></i>
  Home
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-category"></i>
      前端学习
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="/categories/HTML5&amp;CSS3/" class="nav-link"><i class="undefined"></i>
  HTML5&amp;CSS3
</a></li><li class="dropdown-item"><!----> <a href="/categories/Javascript/" class="nav-link"><i class="undefined"></i>
  Javascript
</a></li><li class="dropdown-item"><!----> <a href="/categories/Node/" class="nav-link"><i class="undefined"></i>
  Node
</a></li><li class="dropdown-item"><!----> <a href="/categories/VUE/" class="nav-link"><i class="undefined"></i>
  VUE
</a></li></ul></div></div><div class="nav-item"><a href="/tag/" class="nav-link"><i class="iconfont reco-tag"></i>
  Tags
</a></div><div class="nav-item"><a href="/timeline/" class="nav-link"><i class="iconfont reco-date"></i>
  时间轴
</a></div><div class="nav-item"><div class="dropdown-wrapper"><a class="dropdown-title"><span class="title"><i class="iconfont reco-message"></i>
      联系我
    </span> <span class="arrow right"></span></a> <ul class="nav-dropdown" style="display:none;"><li class="dropdown-item"><!----> <a href="https://github.com/hasakxu" target="_blank" rel="noopener noreferrer" class="nav-link external"><i class="iconfont reco-github"></i>
  GitHub
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></li></ul></div></div> <!----></nav> <!----> </aside> <div class="password-shadow password-wrapper-in" style="display:none;" data-v-59e6cb88 data-v-7dd95ae2><h3 class="title" data-v-59e6cb88>4 数据库与身份认证</h3> <!----> <label id="box" class="inputBox" data-v-59e6cb88><input type="password" value="" data-v-59e6cb88> <span data-v-59e6cb88>Konck! Knock!</span> <button data-v-59e6cb88>OK</button></label> <div class="footer" data-v-59e6cb88><span data-v-59e6cb88><i class="iconfont reco-theme" data-v-59e6cb88></i> <a target="blank" href="https://vuepress-theme-reco.recoluan.com" data-v-59e6cb88>vuePress-theme-reco</a></span> <span data-v-59e6cb88><i class="iconfont reco-copyright" data-v-59e6cb88></i> <a data-v-59e6cb88><span data-v-59e6cb88>hasak</span>
          
        <span data-v-59e6cb88>2022 - </span>
        2023
      </a></span></div></div> <div data-v-7dd95ae2><div data-v-7dd95ae2><main class="page" style="padding-right:0;"><section style="display:;"><div class="page-title"><h1 class="title">4 数据库与身份认证</h1> <div data-v-8a445198><i class="iconfont reco-account" data-v-8a445198><span data-v-8a445198>hasak</span></i> <i class="iconfont reco-date" data-v-8a445198><span data-v-8a445198>6/28/2022</span></i> <!----> <i class="tags iconfont reco-tag" data-v-8a445198><span class="tag-item" data-v-8a445198>Node</span></i></div></div> <div class="theme-reco-content content__default"><h1 id="_4-数据库与身份认证"><a href="#_4-数据库与身份认证" class="header-anchor">#</a> 4 数据库与身份认证</h1> <h2 id="在-express-中操作-mysql"><a href="#在-express-中操作-mysql" class="header-anchor">#</a> 在 Express 中操作 MySQL</h2> <h3 id="在-express-中操作数据库的步骤"><a href="#在-express-中操作数据库的步骤" class="header-anchor">#</a> 在 Express 中操作数据库的步骤</h3> <ol><li><p>安装操作 MySQL 数据库的第三方模块（mysql）</p></li> <li><p>通过 mysql模块连接到 MySQL 数据库</p></li> <li><p>通过 mysql模块执行 SQL 语句</p></li></ol> <h3 id="安装与配置-mysql模块"><a href="#安装与配置-mysql模块" class="header-anchor">#</a> 安装与配置 mysql模块</h3> <p><strong>安装mysql模块</strong></p> <p>mysql模块是托管于 npm 上的第三方模块。它提供了在 Node.js 项目中连接和操作MySQL 数据库的能力
想要在项目中使用它，需要先运行如下命令，将 mysql安装为项目的依赖包</p> <div class="language- line-numbers-mode"><pre class="language-text"><code>npm install mysql
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>配置mysql模块</strong></p> <p>在使用 mysql模块操作 MySQL 数据库之前，必须先对 mysql模块进行必要的配置，主要的配置步骤如下</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> mysql <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'mysql'</span><span class="token punctuation">)</span>	<span class="token comment">// 1. 导入 mysql 模块</span>

<span class="token keyword">const</span> db <span class="token operator">=</span> mysql<span class="token punctuation">.</span><span class="token function">createPool</span><span class="token punctuation">(</span><span class="token punctuation">{</span>		<span class="token comment">// 2. 建立与 MySQL 数据库的连接关系</span>
  <span class="token literal-property property">host</span><span class="token operator">:</span> <span class="token string">'127.0.0.1'</span><span class="token punctuation">,</span>						<span class="token comment">// 数据库的 IP 地址</span>
  <span class="token literal-property property">user</span><span class="token operator">:</span> <span class="token string">'root'</span><span class="token punctuation">,</span>									<span class="token comment">// 登录数据库的账号</span>
  <span class="token literal-property property">password</span><span class="token operator">:</span> <span class="token string">'root'</span><span class="token punctuation">,</span>							<span class="token comment">// 登录数据库的密码</span>
  <span class="token literal-property property">database</span><span class="token operator">:</span> <span class="token string">'my_db_01'</span><span class="token punctuation">,</span>					<span class="token comment">// 指定要操作哪个数据库</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p><strong>测试 mysql模块能否正常工作</strong></p> <p>调用 db.query() 函数，指定要执行的 SQL 语句，通过回调函数拿到执行的结果</p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span><span class="token string">'select 1'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>	<span class="token comment">// 测试 mysql 模块能否正常工作</span>
  <span class="token keyword">if</span><span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>	<span class="token comment">// mysql 模块工作期间报错了</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>results<span class="token punctuation">)</span>										<span class="token comment">// 能够成功的执行 SQL 语句</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br></div></div><h3 id="使用-mysql模块操作-mysql-数据库"><a href="#使用-mysql模块操作-mysql-数据库" class="header-anchor">#</a> 使用 mysql模块操作 MySQL 数据库</h3> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 查询 users 表中所有的数据</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span><span class="token string">'select * from users'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token comment">// 查询成功</span>
  <span class="token comment">// 注意：如果执行的是 select 查询语句，则执行的结果是数组</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>results<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 向 users 表中，插入一条数据</span>
<span class="token keyword">const</span> user <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token literal-property property">username</span><span class="token operator">:</span> <span class="token string">'Spider-Man'</span><span class="token punctuation">,</span> <span class="token literal-property property">password</span><span class="token operator">:</span> <span class="token string">'pcc123'</span> <span class="token punctuation">}</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'insert into users (username, password) values (?, ?)'</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token punctuation">[</span>user<span class="token punctuation">.</span>username<span class="token punctuation">,</span> user<span class="token punctuation">.</span>password<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token comment">// 插入成功</span>
  <span class="token comment">// 注意：如果执行的是 insert into 插入语句，则 results 是一个对象</span>
  <span class="token comment">// 可以通过 affectedRows 属性，来判断是否插入数据成功</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'插入数据成功!'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 插入数据的便捷方式</span>
<span class="token keyword">const</span> user <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token literal-property property">username</span><span class="token operator">:</span> <span class="token string">'Spider-Man2'</span><span class="token punctuation">,</span> <span class="token literal-property property">password</span><span class="token operator">:</span> <span class="token string">'pcc4321'</span> <span class="token punctuation">}</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'insert into users set ?'</span>
<span class="token comment">// 执行 SQL 语句</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> user<span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'插入数据成功'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 更新用户的信息</span>
<span class="token keyword">const</span> user <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token literal-property property">id</span><span class="token operator">:</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token literal-property property">username</span><span class="token operator">:</span> <span class="token string">'aaa'</span><span class="token punctuation">,</span> <span class="token literal-property property">password</span><span class="token operator">:</span> <span class="token string">'000'</span> <span class="token punctuation">}</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'update users set username=?, password=? where id=?'</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token punctuation">[</span>user<span class="token punctuation">.</span>username<span class="token punctuation">,</span> user<span class="token punctuation">.</span>password<span class="token punctuation">,</span> user<span class="token punctuation">.</span>id<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token comment">// 注意：执行了 update 语句之后，结果也是一个对象，也会包含 affectedRows 属性</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'更新成功'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 更新数据的便捷方式</span>
<span class="token keyword">const</span> user <span class="token operator">=</span> <span class="token punctuation">{</span> <span class="token literal-property property">id</span><span class="token operator">:</span> <span class="token number">6</span><span class="token punctuation">,</span> <span class="token literal-property property">username</span><span class="token operator">:</span> <span class="token string">'aaaa'</span><span class="token punctuation">,</span> <span class="token literal-property property">password</span><span class="token operator">:</span> <span class="token string">'0000'</span> <span class="token punctuation">}</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'update users set ? where id=?'</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token punctuation">[</span>user<span class="token punctuation">,</span> user<span class="token punctuation">.</span>id<span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'更新数据成功'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 删除 id 为 5 的用户</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'delete from users where id=?'</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token number">5</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token comment">// 注意：执行 delete 语句之后，结果也是一个对象，也会包含 affectedRows 属性</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'删除数据成功'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 标记删除</span>
<span class="token keyword">const</span> sqlStr <span class="token operator">=</span> <span class="token string">'update users set status=? where id=?'</span>
db<span class="token punctuation">.</span><span class="token function">query</span><span class="token punctuation">(</span>sqlStr<span class="token punctuation">,</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span> <span class="token number">6</span><span class="token punctuation">]</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> results</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">)</span> <span class="token keyword">return</span> console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>err<span class="token punctuation">.</span>message<span class="token punctuation">)</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>results<span class="token punctuation">.</span>affectedRows <span class="token operator">===</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span><span class="token string">'标记删除成功'</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br><span class="line-number">60</span><br><span class="line-number">61</span><br><span class="line-number">62</span><br><span class="line-number">63</span><br><span class="line-number">64</span><br><span class="line-number">65</span><br><span class="line-number">66</span><br><span class="line-number">67</span><br><span class="line-number">68</span><br><span class="line-number">69</span><br><span class="line-number">70</span><br><span class="line-number">71</span><br></div></div><h2 id="前后端的身份认证"><a href="#前后端的身份认证" class="header-anchor">#</a> 前后端的身份认证</h2> <h3 id="web-开发模式"><a href="#web-开发模式" class="header-anchor">#</a> Web 开发模式</h3> <p>目前主流的 Web 开发模式有两种，分别是</p> <ul><li>基于<strong>服务端渲染</strong>的传统 Web 开发模式</li> <li>基于<strong>前后端分离</strong>的新型 Web 开发模式</li></ul> <h3 id="服务端渲染的-web-开发模式"><a href="#服务端渲染的-web-开发模式" class="header-anchor">#</a> 服务端渲染的 Web 开发模式</h3> <p>**服务端渲染的概念：**服务器发送给客户端的 HTML 页面，是在服务器通过字符串的拼接，动态生成的。因此，客户端不需要使用 Ajax 这样的技术额外请求页面的数据。</p> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191602302.png" alt="image.png"></p> <p><strong>优点</strong></p> <ul><li><p><strong>前端耗时少</strong>，服务器端负责动态生成 HTML 内容，浏览器只需直接渲染页面即可。尤其是移动端，更省电</p></li> <li><p><strong>有利于SEO</strong>，服务器端响应的是完整的 HTML 页面内容，所以爬虫更容易爬取获得信息，更有利于 SEO</p></li></ul> <p><strong>缺点</strong></p> <ul><li><p><strong>占用服务器端资源</strong>，服务器端完成 HTML 页面内容的拼接，如果请求较多，会对服务器造成一定的访问压力</p></li> <li><p><strong>不利于前后端分离，开发效率低</strong>，使用服务器端渲染，则<strong>无法进行分工合作</strong>，尤其对于前端复杂度高的项目，不利于项目高效开发</p></li></ul> <p><strong>前后端分离的 Web 开发模式</strong></p> <p><strong>前后端分离的概念</strong>：前后端分离的开发模式，依赖于 Ajax 技术的广泛应用。简而言之，前后端分离的 Web 开发模式，就是后端只负责提供 API 接口，前端使用 Ajax 调用接口的开发模式。</p> <p><strong>优点</strong></p> <ul><li>**开发体验好，**前端专注于 UI 页面的开发，后端专注于api的开发，且前端有更多的选择性</li> <li>**用户体验好，**Ajax 技术的广泛应用，极大的提高了用户的体验，可以轻松实现页面的局部刷新</li> <li>**减轻了服务器端的渲染压力，**因为页面最终是在每个用户的浏览器中生成的</li></ul> <p><strong>缺点</strong></p> <ul><li><strong>不利于 SEO</strong>，因为完整的 HTML 页面需要在客户端动态拼接完成，所以爬虫对无法爬取页面的有效信息。（解决方案：利用 Vue、React 等前端框架的 SSR（server side render）技术能够很好的解决 SEO 问题！）</li></ul> <p><strong>如何选择 Web 开发模式</strong></p> <p>==不谈业务场景而盲目选择使用何种开发模式都是耍流氓==</p> <ul><li>比如企业级网站，主要功能是展示而没有复杂的交互，需要良好的 SEO，这时就需要使用服务器端渲染</li> <li>而类似后台管理项目，交互性比较强，不需要考虑 SEO，那么就可以使用前后端分离的开发模式</li> <li>另外，具体使用何种开发模式并不是绝对的，为了<strong>同时兼顾</strong>了<strong>首页的渲染速度</strong>和<strong>前后端分离的开发效率</strong>，一些网站采用了首屏服务器端渲染 + 其他页面前后端分离的开发模式</li></ul> <h3 id="身份认证"><a href="#身份认证" class="header-anchor">#</a> 身份认证</h3> <p><strong>身份认证（Authentication）<strong>又称身份验证、鉴权，是指</strong>通过一定的手段，完成对用户身份的确认</strong></p> <ul><li>日常生活中的身份认证随处可见，如高铁的验票乘车，手机的密码或指纹解锁，支付宝或微信的支付密码等</li> <li>在 Web 开发中，也涉及到用户身份的认证，如各大网站的手机验证码登录、邮箱密码登录、二维码登录等</li></ul> <p><strong>不同开发模式下的身份认证</strong></p> <ul><li>对于服务端渲染和前后端分离这两种开发模式来说，分别有着不同的身份认证方案
<ul><li><strong>服务端渲染</strong>推荐使用 <strong>Session</strong> 认证机制</li> <li><strong>前后端分离</strong>推荐使用 <strong>JWT</strong> 认证机制</li></ul></li></ul> <h3 id="session-认证机制"><a href="#session-认证机制" class="header-anchor">#</a> Session 认证机制</h3> <p><strong>HTTP 协议的无状态性</strong></p> <blockquote><p>HTTP 协议的无状态性，指的是客户端的每次 HTTP 请求都是独立的，连续多个请求之间没有直接的关系，服务器不会主动保留每次 HTTP 请求的状态。</p> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191605891.png" alt="image.png"></p> <p>如何突破 HTTP 无状态的限制</p> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191605906.png" alt="image.png"></p></blockquote> <p><strong>Cookie</strong></p> <blockquote><p>Cookie 是存储在用户浏览器中的一段不超过 4 KB 的字符串。它由一个名称（Name）、一个值（Value）和其它几个用于控制 Cookie 有效期、安全性、使用范围的可选属性组成。不同域名下的 Cookie 各自独立，每当客户端发起请求时，会自动把当前域名下所有未过期的 Cookie 一同发送到服务器。
Cookie的几大特性：自动发送、域名独立、过期时限、4KB 限制
客户端第一次请求服务器的时候，服务器<strong>通过响应头的形式</strong>，向客户端发送一个身份认证的 Cookie，客户端会自动将 Cookie 保存在浏览器中。
随后，当客户端浏览器每次请求服务器的时候，浏览器会<strong>自动</strong>将身份认证相关的 Cookie，<strong>通过请求头的形式</strong>发送给服务器，服务器即可验明客户端的身份。
Cookie 不具有安全性
由于 Cookie 是存储在浏览器中的，而且<strong>浏览器也提供了读写 Cookie 的 API</strong>，因此 <strong>Cookie 很容易被伪造</strong>，不具有安全性。因此不建议服务器将重要的隐私数据，通过 Cookie 的形式发送给浏览器。</p></blockquote> <p><strong>Session</strong></p> <blockquote><p>提高身份认证的安全性
为了防止客户伪造会员卡，收银员在拿到客户出示的会员卡之后，可以在收银机上进行刷卡认证。只有收银机确认存在的会员卡，才能被正常使用。
Session的工作原理</p></blockquote> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191606143.png" alt="image.png"></p> <h3 id="在-express-中使用-session-认证"><a href="#在-express-中使用-session-认证" class="header-anchor">#</a> 在 Express 中使用 Session 认证</h3> <p><strong>安装express-session 中间件</strong></p> <div class="language- line-numbers-mode"><pre class="language-text"><code>npm install express-session
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>配置 express-session 中间件</strong></p> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express'</span><span class="token punctuation">)</span>
<span class="token keyword">const</span> session <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token string">'express-session'</span><span class="token punctuation">)</span>	<span class="token comment">// 配置 Session 中间件</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token function">session</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
  <span class="token literal-property property">secret</span><span class="token operator">:</span> <span class="token string">'itheima'</span><span class="token punctuation">,</span>				<span class="token comment">// 字符串，负责对session加密的</span>
  <span class="token literal-property property">resave</span><span class="token operator">:</span> <span class="token boolean">false</span><span class="token punctuation">,</span>
  <span class="token literal-property property">saveUninitialized</span><span class="token operator">:</span> <span class="token boolean">true</span><span class="token punctuation">,</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p><strong>向 session 中存数据</strong></p> <ul><li>当<code>express-session</code> 中间件配置成功后，可通过 <code>req.session</code>来访问和使用 session 对象，从而存储用户的关键信息</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>
<span class="token comment">// 登录的 API 接口</span>
app<span class="token punctuation">.</span><span class="token function">post</span><span class="token punctuation">(</span><span class="token string">'/api/login'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 判断登录信息是否正确</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>req<span class="token punctuation">.</span>body<span class="token punctuation">.</span>username <span class="token operator">!==</span> <span class="token string">'admin'</span> <span class="token operator">||</span> req<span class="token punctuation">.</span>body<span class="token punctuation">.</span>password <span class="token operator">!==</span> <span class="token string">'000000'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token literal-property property">msg</span><span class="token operator">:</span> <span class="token string">'登录失败'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>

  <span class="token comment">// 登录成功后的用户信息，保存到 Session 中</span>
  <span class="token comment">// 只有成功配置了 express-session 中间件之后，req 才能点出来 session 这个属性</span>
  req<span class="token punctuation">.</span>session<span class="token punctuation">.</span>user <span class="token operator">=</span> req<span class="token punctuation">.</span>body <span class="token comment">// 用户的信息</span>
  req<span class="token punctuation">.</span>session<span class="token punctuation">.</span>islogin <span class="token operator">=</span> <span class="token boolean">true</span> <span class="token comment">// 用户的登录状态</span>

  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">,</span> <span class="token literal-property property">msg</span><span class="token operator">:</span> <span class="token string">'登录成功'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br></div></div><p><strong>从 session 中取数据</strong></p> <ul><li>可以直接从 req.session 对象上获取之前存储的数据</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 获取用户姓名的接口</span>
app<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'/api/username'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 从 Session 中获取用户的名称，响应给客户端</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token operator">!</span>req<span class="token punctuation">.</span>session<span class="token punctuation">.</span>islogin<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">1</span><span class="token punctuation">,</span> <span class="token literal-property property">msg</span><span class="token operator">:</span> <span class="token string">'fail'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">,</span>
    <span class="token literal-property property">msg</span><span class="token operator">:</span> <span class="token string">'success'</span><span class="token punctuation">,</span>
    <span class="token literal-property property">username</span><span class="token operator">:</span> req<span class="token punctuation">.</span>session<span class="token punctuation">.</span>user<span class="token punctuation">.</span>username<span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br></div></div><p><strong>清空 session</strong></p> <ul><li>调用 req.session.destroy() 函数，即可清空服务器保存的 session 信息</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 退出登录的接口</span>
app<span class="token punctuation">.</span><span class="token function">post</span><span class="token punctuation">(</span><span class="token string">'/api/logout'</span><span class="token punctuation">,</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 清空 Session 信息</span>
  req<span class="token punctuation">.</span>session<span class="token punctuation">.</span><span class="token function">destroy</span><span class="token punctuation">(</span><span class="token punctuation">)</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">0</span><span class="token punctuation">,</span>
    <span class="token literal-property property">msg</span><span class="token operator">:</span> <span class="token string">'退出登录成功'</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br></div></div><p><strong>了解 Session 认证的局限性</strong></p> <ul><li>Session 认证机制需要配合 Cookie 才能实现。由于 Cookie 默认不支持跨域访问，所以，当涉及到前端跨域请求后端接口的时候，需要做很多额外的配置，才能实现跨域 Session 认证
<ul><li>当前端请求后端接口不存在跨域问题的时候，推荐使用 Session 身份认证机制</li> <li>当前端需要跨域请求后端接口的时候，不推荐使用 Session 身份认证机制，推荐使用 JWT 认证机制</li></ul></li></ul> <h3 id="jwt-认证机制"><a href="#jwt-认证机制" class="header-anchor">#</a> JWT 认证机制</h3> <p>**JWT（JSON Web Token）**是目前最流行的跨域认证解决方案</p> <p>官网 https://jwt.io/</p> <p><strong>JWT 的工作原理</strong></p> <ul><li>总结：用户的信息通过 Token 字符串的形式，保存在客户端浏览器中。服务器通过还原 Token 字符串的形式来认证用户的身份。</li></ul> <img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191608856.png" alt="image.png" style="zoom:67%;"> <p><strong>JWT 的组成部分</strong></p> <ul><li>JWT 通常由三部分组成，分别是 Header（头部）、Payload（有效荷载）、Signature（签名），会将JWT的3部分分别进行Base64编码后用“.”分隔</li></ul> <div class="language- line-numbers-mode"><pre class="language-text"><code>Header.Payload.Signature
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>JWT 的三个部分各自代表的含义</strong></p> <ul><li>Header 是一个描述JWT元数据的JSON对象，alg属性表示签名使用的算法，默认为HMAC SHA256（写为HS256）；typ属性表示令牌的类型，JWT令牌统一写为JWT。最后，使用Base64 URL算法将上述JSON对象转换为字符串保存</li></ul> <div class="language-json line-numbers-mode"><pre class="language-json"><code><span class="token punctuation">{</span>
  <span class="token property">&quot;alg&quot;</span><span class="token operator">:</span> <span class="token string">&quot;HS256&quot;</span><span class="token punctuation">,</span>
  <span class="token property">&quot;typ&quot;</span><span class="token operator">:</span> <span class="token string">&quot;JWT&quot;</span>
<span class="token punctuation">}</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><ul><li><p><code>Payload</code> 部分才是真正的用户信息，它是用户信息经过加密之后生成的 JSON 字符串</p></li> <li><p><code>Signature</code>是对上面两部分数据签名，需要使用 base64 编码后的 <code>header</code> 和 <code>payload</code>数据，通过指定的算法生成哈希，以确保数据不会被篡改。首先，需要指定一个密钥（secret）。该密码仅仅为保存在服务器中，并且不能向用户公开。然后，使用header中指定的签名算法（默认情况下为HMAC SHA256）根据以下公式生成签名</p></li></ul> <p><code>HMACSHA256(base64UrlEncode(header)+&quot;.&quot;+base64UrlEncode(payload),secret)</code></p> <p>​		请注意，默认情况下JWT是未加密的，因为只是采用base64算法，拿到JWT字符串后可以转换回		原本的JSON数据，任何人都可以解读其内容，因此不要构建隐私信息字段，比如用户的密码一		定不能保存到JWT中，以防止信息泄露。JWT只是适合在网络中传输一些非敏感的信息</p> <p><strong>JWT 的使用方式</strong></p> <ul><li>客户端收到服务器返回的 JWT 之后，通常会将它储存在 localStorage或 sessionStorage中。此后，客户端每次与服务器通信，都要带上这个 JWT 的字符串，从而进行身份认证。推荐的做法是把 JWT 放在 HTTP 请求头的 Authorization 字段中</li></ul> <p><img src="https://hasakwebblogimg.oss-cn-hangzhou.aliyuncs.com/202211191609584.png" alt="image.png"></p> <h3 id="在-express-中使用-jwt"><a href="#在-express-中使用-jwt" class="header-anchor">#</a> 在 Express 中使用 JWT</h3> <p><strong>安装JWT 相关的包</strong></p> <ul><li><code>jsonwebtoken</code>用于<strong>生成 JWT 字符串</strong></li> <li><code>express-jwt</code> 用于将 <strong>JWT 字符串解析还原成 JSON 对象</strong></li></ul> <div class="language- line-numbers-mode"><pre class="language-text"><code>npm install jsonwebtoken express-jwt
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br></div></div><p><strong>导入JWT 相关的包</strong></p> <ul><li>使用 require() 函数，分别导入 JWT 相关的两个包</li></ul> <div class="language- line-numbers-mode"><pre class="language-text"><code>const jwt = require('jsonwebtoken')
const expressJWT = require('express-jwt')
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>定义 secret 密钥</strong></p> <ul><li>为了保证 JWT 字符串的安全性，防止 JWT 字符串在网络传输过程中被别人破解，我们需要专门定义一个用于加密和解密的 secret 密钥
<ul><li>当生成 JWT 字符串的时候，需使用 secret 密钥对用户的信息进行加密，最终得到加密好的 JWT 字符串</li> <li>当把 JWT 字符串解析还原成 JSON 对象的时候，需要使用 secret 密钥进行解密</li></ul></li></ul> <div class="language-java line-numbers-mode"><pre class="language-java"><code><span class="token comment">// TODO_02：定义 secret 密钥，建议将密钥命名为 secretKey</span>
<span class="token keyword">const</span> secretKey <span class="token operator">=</span> 'itheima <span class="token class-name">No1</span> <span class="token operator">^</span>_<span class="token operator">^</span>'
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br></div></div><p><strong>在登录成功后生成 JWT 字符串</strong></p> <ul><li>调用 jsonwebtoken 包提供的 sign() 方法，将用户的信息加密成 JWT 字符串，响应给客户端</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code>
<span class="token comment">// 登录接口</span>
app<span class="token punctuation">.</span><span class="token function">post</span><span class="token punctuation">(</span><span class="token string">'/api/login'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token keyword">const</span> userinfo <span class="token operator">=</span> req<span class="token punctuation">.</span>body	<span class="token comment">// 将 req.body 请求体中的数据，转存为 userinfo 常量</span>
      
  <span class="token comment">// 登录失败</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>userinfo<span class="token punctuation">.</span>username <span class="token operator">!==</span> <span class="token string">'admin'</span> <span class="token operator">||</span> userinfo<span class="token punctuation">.</span>password <span class="token operator">!==</span> <span class="token string">'000000'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">400</span><span class="token punctuation">,</span>
      <span class="token literal-property property">message</span><span class="token operator">:</span> <span class="token string">'登录失败！'</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
    
  <span class="token comment">// 在登录成功之后，调用 jwt.sign() 方法生成 JWT 字符串。并通过 token 属性发送给客户端</span>
  <span class="token comment">// 参数1：用户的信息对象</span>
  <span class="token comment">// 参数2：加密的秘钥</span>
  <span class="token comment">// 参数3：配置对象，可以配置当前 token 的有效期</span>
  <span class="token comment">// 记住：千万不要把密码加密到 token 字符中</span>
  <span class="token keyword">const</span> tokenStr <span class="token operator">=</span> jwt<span class="token punctuation">.</span><span class="token function">sign</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token literal-property property">username</span><span class="token operator">:</span> userinfo<span class="token punctuation">.</span>username<span class="token punctuation">}</span><span class="token punctuation">,</span> secretKey<span class="token punctuation">,</span> <span class="token punctuation">{</span><span class="token literal-property property">expiresIn</span><span class="token operator">:</span> <span class="token string">'30s'</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
    <span class="token literal-property property">message</span><span class="token operator">:</span> <span class="token string">'登录成功！'</span><span class="token punctuation">,</span>
    <span class="token literal-property property">token</span><span class="token operator">:</span> tokenStr<span class="token punctuation">,</span>		<span class="token comment">// 要发送给客户端的 token 字符串</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br></div></div><p><strong>将 JWT 字符串还原为 JSON 对象</strong></p> <ul><li>客户端每次在访问那些有权限接口的时候，都需要主动通过请求头中的 <strong>Authorization</strong> 字段，将 Token 字符串发送到服务器进行身份认证。</li> <li>此时，服务器可以通过 <strong>express-jwt</strong> 这个中间件，自动将客户端发送过来的 Token 解析还原成 JSON 对象</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 将 JWT 字符串解析还原成 JSON 对象的中间件</span>
<span class="token comment">// 只要配置成功了 express-jwt 这个中间件，就可以把解析出来的用户信息，挂载到 req.user 属性上</span>
<span class="token comment">// unless() 指定哪些不需要访问权限</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token function">expressJWT</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token literal-property property">secret</span><span class="token operator">:</span> secretKey <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unless</span><span class="token punctuation">(</span><span class="token punctuation">{</span> <span class="token literal-property property">path</span><span class="token operator">:</span> <span class="token punctuation">[</span><span class="token regex"><span class="token regex-delimiter">/</span><span class="token regex-source language-regex">^\/api\/</span><span class="token regex-delimiter">/</span></span><span class="token punctuation">]</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br></div></div><p><strong>使用 req.user 获取用户信息</strong></p> <ul><li>当 express-jwt 这个中间件配置成功之后，即可在那些有权限的接口中，使用 req.user 对象，来访问从 JWT 字符串中解析出来的用户信息了</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 这是一个有权限的 API 接口</span>
app<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token string">'/admin/getinfo'</span><span class="token punctuation">,</span> <span class="token keyword">function</span> <span class="token punctuation">(</span><span class="token parameter">req<span class="token punctuation">,</span> res</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 使用 req.user 获取用户信息，并使用 data 属性将用户信息发送给客户端</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>user<span class="token punctuation">)</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    <span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
    <span class="token literal-property property">message</span><span class="token operator">:</span> <span class="token string">'获取用户信息成功！'</span><span class="token punctuation">,</span>
    <span class="token literal-property property">data</span><span class="token operator">:</span> req<span class="token punctuation">.</span>user<span class="token punctuation">,</span>			<span class="token comment">// 要发送给客户端的用户信息</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br></div></div><p><strong>捕获解析 JWT 失败后产生的错误</strong></p> <ul><li>当使用 express-jwt 解析 Token 字符串时，如果客户端发送过来的 Token 字符串<strong>过期</strong>或<strong>不合法</strong>，会产生一个解析失败的错误，影响项目的正常运行。我们可以通过 Express 的错误中间件，捕获这个错误并进行相关的处理</li></ul> <div class="language-javascript line-numbers-mode"><pre class="language-javascript"><code><span class="token comment">// 使用全局错误处理中间件，捕获解析 JWT 失败后产生的错误</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token parameter">err<span class="token punctuation">,</span> req<span class="token punctuation">,</span> res<span class="token punctuation">,</span> next</span><span class="token punctuation">)</span> <span class="token operator">=&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 这次错误是由 token 解析失败导致的</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">.</span>name <span class="token operator">===</span> <span class="token string">'UnauthorizedError'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">401</span><span class="token punctuation">,</span><span class="token literal-property property">message</span><span class="token operator">:</span> <span class="token string">'无效的token'</span><span class="token punctuation">,</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span><span class="token literal-property property">status</span><span class="token operator">:</span> <span class="token number">500</span><span class="token punctuation">,</span><span class="token literal-property property">message</span><span class="token operator">:</span> <span class="token string">'未知的错误'</span><span class="token punctuation">,</span><span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>
</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br></div></div><p><strong>综合</strong></p> <div class="language-java line-numbers-mode"><pre class="language-java"><code>
<span class="token keyword">const</span> express <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span>'express'<span class="token punctuation">)</span>
<span class="token keyword">const</span> app <span class="token operator">=</span> <span class="token function">express</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

<span class="token comment">// 安装并导入 JWT 相关的两个包，分别是 jsonwebtoken 和 express-jwt</span>
<span class="token keyword">const</span> jwt <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span>'jsonwebtoken'<span class="token punctuation">)</span>
<span class="token keyword">const</span> expressJWT <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span>'express<span class="token operator">-</span>jwt'<span class="token punctuation">)</span>

<span class="token comment">// 允许跨域资源共享</span>
<span class="token keyword">const</span> cors <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span><span class="token char">'cors'</span><span class="token punctuation">)</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token function">cors</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment">// 解析 post 表单数据的中间件</span>
<span class="token keyword">const</span> bodyParser <span class="token operator">=</span> <span class="token function">require</span><span class="token punctuation">(</span>'body<span class="token operator">-</span>parser'<span class="token punctuation">)</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span>bodyParser<span class="token punctuation">.</span><span class="token function">urlencoded</span><span class="token punctuation">(</span><span class="token punctuation">{</span> extended<span class="token operator">:</span> <span class="token boolean">false</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment">// TODO_02：定义 secret 密钥，建议将密钥命名为 secretKey</span>
<span class="token keyword">const</span> secretKey <span class="token operator">=</span> 'itheima <span class="token class-name">No1</span> <span class="token operator">^</span>_<span class="token operator">^</span>'

<span class="token comment">// TODO_04：注册将 JWT 字符串解析还原成 JSON 对象的中间件</span>
<span class="token comment">// 注意：只要配置成功了 express-jwt 这个中间件，就可以把解析出来的用户信息，挂载到 req.user 属性上</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token function">expressJWT</span><span class="token punctuation">(</span><span class="token punctuation">{</span> secret<span class="token operator">:</span> secretKey <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">unless</span><span class="token punctuation">(</span><span class="token punctuation">{</span> path<span class="token operator">:</span> <span class="token punctuation">[</span><span class="token operator">/</span><span class="token operator">^</span>\<span class="token operator">/</span>api\<span class="token operator">/</span><span class="token operator">/</span><span class="token punctuation">]</span> <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">)</span>

<span class="token comment">// 登录接口</span>
app<span class="token punctuation">.</span><span class="token function">post</span><span class="token punctuation">(</span>'<span class="token operator">/</span>api<span class="token operator">/</span>login'<span class="token punctuation">,</span> function <span class="token punctuation">(</span>req<span class="token punctuation">,</span> res<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// 将 req.body 请求体中的数据，转存为 userinfo 常量</span>
  <span class="token keyword">const</span> userinfo <span class="token operator">=</span> req<span class="token punctuation">.</span>body
  <span class="token comment">// 登录失败</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>userinfo<span class="token punctuation">.</span>username <span class="token operator">!=</span><span class="token operator">=</span> <span class="token char">'admin'</span> <span class="token operator">||</span> userinfo<span class="token punctuation">.</span>password <span class="token operator">!=</span><span class="token operator">=</span> <span class="token char">'000000'</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      status<span class="token operator">:</span> <span class="token number">400</span><span class="token punctuation">,</span>
      message<span class="token operator">:</span> <span class="token char">'登录失败！'</span><span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  <span class="token comment">// 登录成功</span>
  <span class="token comment">// TODO_03：在登录成功之后，调用 jwt.sign() 方法生成 JWT 字符串。并通过 token 属性发送给客户端</span>
  <span class="token comment">// 参数1：用户的信息对象</span>
  <span class="token comment">// 参数2：加密的秘钥</span>
  <span class="token comment">// 参数3：配置对象，可以配置当前 token 的有效期</span>
  <span class="token comment">// 记住：千万不要把密码加密到 token 字符中</span>
  <span class="token keyword">const</span> tokenStr <span class="token operator">=</span> jwt<span class="token punctuation">.</span><span class="token function">sign</span><span class="token punctuation">(</span><span class="token punctuation">{</span> username<span class="token operator">:</span> userinfo<span class="token punctuation">.</span>username <span class="token punctuation">}</span><span class="token punctuation">,</span> secretKey<span class="token punctuation">,</span> <span class="token punctuation">{</span> expiresIn<span class="token operator">:</span> <span class="token char">'30s'</span> <span class="token punctuation">}</span><span class="token punctuation">)</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    status<span class="token operator">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
    message<span class="token operator">:</span> <span class="token char">'登录成功！'</span><span class="token punctuation">,</span>
    token<span class="token operator">:</span> tokenStr<span class="token punctuation">,</span> <span class="token comment">// 要发送给客户端的 token 字符串</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 这是一个有权限的 API 接口</span>
app<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span>'<span class="token operator">/</span>admin<span class="token operator">/</span>getinfo'<span class="token punctuation">,</span> function <span class="token punctuation">(</span>req<span class="token punctuation">,</span> res<span class="token punctuation">)</span> <span class="token punctuation">{</span>
  <span class="token comment">// TODO_05：使用 req.user 获取用户信息，并使用 data 属性将用户信息发送给客户端</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>req<span class="token punctuation">.</span>user<span class="token punctuation">)</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    status<span class="token operator">:</span> <span class="token number">200</span><span class="token punctuation">,</span>
    message<span class="token operator">:</span> '获取用户信息成功！'<span class="token punctuation">,</span>
    data<span class="token operator">:</span> req<span class="token punctuation">.</span>user<span class="token punctuation">,</span> <span class="token comment">// 要发送给客户端的用户信息</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// TODO_06：使用全局错误处理中间件，捕获解析 JWT 失败后产生的错误</span>
app<span class="token punctuation">.</span><span class="token function">use</span><span class="token punctuation">(</span><span class="token punctuation">(</span>err<span class="token punctuation">,</span> req<span class="token punctuation">,</span> res<span class="token punctuation">,</span> next<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">&gt;</span> <span class="token punctuation">{</span>
  <span class="token comment">// 这次错误是由 token 解析失败导致的</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>err<span class="token punctuation">.</span>name <span class="token operator">==</span><span class="token operator">=</span> '<span class="token class-name">UnauthorizedError</span>'<span class="token punctuation">)</span> <span class="token punctuation">{</span>
    <span class="token keyword">return</span> res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
      status<span class="token operator">:</span> <span class="token number">401</span><span class="token punctuation">,</span>
      message<span class="token operator">:</span> '无效的token'<span class="token punctuation">,</span>
    <span class="token punctuation">}</span><span class="token punctuation">)</span>
  <span class="token punctuation">}</span>
  res<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span><span class="token punctuation">{</span>
    status<span class="token operator">:</span> <span class="token number">500</span><span class="token punctuation">,</span>
    message<span class="token operator">:</span> <span class="token char">'未知的错误'</span><span class="token punctuation">,</span>
  <span class="token punctuation">}</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

<span class="token comment">// 调用 app.listen 方法，指定端口号并启动web服务器</span>
app<span class="token punctuation">.</span><span class="token function">listen</span><span class="token punctuation">(</span><span class="token number">8888</span><span class="token punctuation">,</span> function <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
  console<span class="token punctuation">.</span><span class="token function">log</span><span class="token punctuation">(</span>'<span class="token class-name">Express</span> server running at http<span class="token operator">:</span><span class="token operator">/</span><span class="token operator">/</span><span class="token number">127.0</span><span class="token number">.0</span><span class="token number">.1</span><span class="token operator">:</span><span class="token number">8888</span>'<span class="token punctuation">)</span>
<span class="token punctuation">}</span><span class="token punctuation">)</span>

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br><span class="line-number">31</span><br><span class="line-number">32</span><br><span class="line-number">33</span><br><span class="line-number">34</span><br><span class="line-number">35</span><br><span class="line-number">36</span><br><span class="line-number">37</span><br><span class="line-number">38</span><br><span class="line-number">39</span><br><span class="line-number">40</span><br><span class="line-number">41</span><br><span class="line-number">42</span><br><span class="line-number">43</span><br><span class="line-number">44</span><br><span class="line-number">45</span><br><span class="line-number">46</span><br><span class="line-number">47</span><br><span class="line-number">48</span><br><span class="line-number">49</span><br><span class="line-number">50</span><br><span class="line-number">51</span><br><span class="line-number">52</span><br><span class="line-number">53</span><br><span class="line-number">54</span><br><span class="line-number">55</span><br><span class="line-number">56</span><br><span class="line-number">57</span><br><span class="line-number">58</span><br><span class="line-number">59</span><br><span class="line-number">60</span><br><span class="line-number">61</span><br><span class="line-number">62</span><br><span class="line-number">63</span><br><span class="line-number">64</span><br><span class="line-number">65</span><br><span class="line-number">66</span><br><span class="line-number">67</span><br><span class="line-number">68</span><br><span class="line-number">69</span><br><span class="line-number">70</span><br><span class="line-number">71</span><br><span class="line-number">72</span><br><span class="line-number">73</span><br><span class="line-number">74</span><br><span class="line-number">75</span><br><span class="line-number">76</span><br><span class="line-number">77</span><br><span class="line-number">78</span><br><span class="line-number">79</span><br></div></div><p>客户端发送token的时候前面需要加 &quot;Bearer &quot; + token</p> <h2 id="java-开发中-jwt-的应用"><a href="#java-开发中-jwt-的应用" class="header-anchor">#</a> Java 开发中 JWT 的应用</h2> <p>在实际的SpringBoot项目中，一般我们可以用如下流程做登录</p> <ol><li><p>在登录验证通过后，给用户生成一个对应的随机 token（注意这个token不是指 JWT，可以用uuid等算法生成），然后将这个token作为key的一部分，用户信息作为value存入Redis，并设置过期时间，这个过期时间就是登录失效的时间</p></li> <li><p>将第1步中生成的随机 token 作为 JWT 的 payload 生成 JWT 字符串返回给前端</p></li> <li><p>前端之后每次请求都在请求头中的 <strong>Authorization</strong> 字段中携带 JWT 字符串</p></li> <li><p>后端定义一个拦截器，每次收到前端请求时，都先从请求头中的 Authorization 字段中取出 JWT 字符串并进行验证，验证通过后解析出 payload 中的随机 token，然后再用这个随机 token 得到 key，从 Redis 中获取用户信息，如果能获取到就说明用户已经登录</p></li></ol> <div class="language-java line-numbers-mode"><pre class="language-java"><code>
<span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">JWTInterceptor</span> <span class="token keyword">implements</span> <span class="token class-name">HandlerInterceptor</span> <span class="token punctuation">{</span>
  <span class="token annotation punctuation">@Override</span>
  <span class="token keyword">public</span> <span class="token keyword">boolean</span> <span class="token function">preHandle</span><span class="token punctuation">(</span><span class="token class-name">HttpServletRequest</span> request<span class="token punctuation">,</span> 
                           <span class="token class-name">HttpServletResponse</span> response<span class="token punctuation">,</span> 
                           <span class="token class-name">Object</span> handler<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
    <span class="token class-name">String</span> <span class="token constant">JWT</span> <span class="token operator">=</span> request<span class="token punctuation">.</span><span class="token function">getHeader</span><span class="token punctuation">(</span><span class="token string">&quot;Authorization&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token keyword">try</span> <span class="token punctuation">{</span>
      <span class="token comment">// 1.校验JWT字符串</span>
      <span class="token class-name">DecodedJWT</span> decodedJWT <span class="token operator">=</span> <span class="token class-name">JWTUtils</span><span class="token punctuation">.</span><span class="token function">decode</span><span class="token punctuation">(</span><span class="token constant">JWT</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      <span class="token comment">// 2.取出JWT字符串载荷中的随机token，从Redis中获取用户信息</span>
      <span class="token punctuation">.</span><span class="token punctuation">.</span><span class="token punctuation">.</span>
        <span class="token keyword">return</span> <span class="token boolean">true</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">SignatureVerificationException</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;无效签名&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">TokenExpiredException</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;token已经过期&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">AlgorithmMismatchException</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;算法不一致&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span><span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">Exception</span> e<span class="token punctuation">)</span><span class="token punctuation">{</span>
      <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;token无效&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
      e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
    <span class="token punctuation">}</span>
    <span class="token keyword">return</span> <span class="token boolean">false</span><span class="token punctuation">;</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span>

</code></pre> <div class="line-numbers-wrapper"><span class="line-number">1</span><br><span class="line-number">2</span><br><span class="line-number">3</span><br><span class="line-number">4</span><br><span class="line-number">5</span><br><span class="line-number">6</span><br><span class="line-number">7</span><br><span class="line-number">8</span><br><span class="line-number">9</span><br><span class="line-number">10</span><br><span class="line-number">11</span><br><span class="line-number">12</span><br><span class="line-number">13</span><br><span class="line-number">14</span><br><span class="line-number">15</span><br><span class="line-number">16</span><br><span class="line-number">17</span><br><span class="line-number">18</span><br><span class="line-number">19</span><br><span class="line-number">20</span><br><span class="line-number">21</span><br><span class="line-number">22</span><br><span class="line-number">23</span><br><span class="line-number">24</span><br><span class="line-number">25</span><br><span class="line-number">26</span><br><span class="line-number">27</span><br><span class="line-number">28</span><br><span class="line-number">29</span><br><span class="line-number">30</span><br></div></div></div></section> <footer class="page-edit"><!----> <!----></footer> <!----> <div class="comments-wrapper"><!----></div></main></div> <!----></div> <ul class="sub-sidebar sub-sidebar-wrapper" style="width:0;" data-v-b57cc07c data-v-7dd95ae2></ul></div></div></div><div class="global-ui"><div class="back-to-ceiling" style="right:1rem;bottom:6rem;width:2.5rem;height:2.5rem;border-radius:.25rem;line-height:2.5rem;display:none;" data-v-c6073ba8 data-v-c6073ba8><svg t="1574745035067" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="5404" class="icon" data-v-c6073ba8><path d="M526.60727968 10.90185116a27.675 27.675 0 0 0-29.21455937 0c-131.36607665 82.28402758-218.69155461 228.01873535-218.69155402 394.07834331a462.20625001 462.20625001 0 0 0 5.36959153 69.94390903c1.00431239 6.55289093-0.34802892 13.13561351-3.76865779 18.80351572-32.63518765 54.11355614-51.75690182 118.55860487-51.7569018 187.94566865a371.06718723 371.06718723 0 0 0 11.50484808 91.98906777c6.53300375 25.50556257 41.68394495 28.14064038 52.69160883 4.22606766 17.37162448-37.73630017 42.14135425-72.50938081 72.80769204-103.21549295 2.18761121 3.04276886 4.15646224 6.24463696 6.40373557 9.22774369a1871.4375 1871.4375 0 0 0 140.04691725 5.34970492 1866.36093723 1866.36093723 0 0 0 140.04691723-5.34970492c2.24727335-2.98310674 4.21612437-6.18497483 6.3937923-9.2178004 30.66633723 30.70611158 55.4360664 65.4791928 72.80769147 103.21549355 11.00766384 23.91457269 46.15860503 21.27949489 52.69160879-4.22606768a371.15156223 371.15156223 0 0 0 11.514792-91.99901164c0-69.36717486-19.13165746-133.82216804-51.75690182-187.92578088-3.42062944-5.66790279-4.76302748-12.26056868-3.76865837-18.80351632a462.20625001 462.20625001 0 0 0 5.36959269-69.943909c-0.00994388-166.08943902-87.32547796-311.81420293-218.6915546-394.09823051zM605.93803103 357.87693858a93.93749974 93.93749974 0 1 1-187.89594924 6.1e-7 93.93749974 93.93749974 0 0 1 187.89594924-6.1e-7z" p-id="5405" data-v-c6073ba8></path><path d="M429.50777625 765.63860547C429.50777625 803.39355007 466.44236686 1000.39046097 512.00932183 1000.39046097c45.56695499 0 82.4922232-197.00623328 82.5015456-234.7518555 0-37.75494459-36.9345906-68.35043303-82.4922232-68.34111062-45.57627738-0.00932239-82.52019037 30.59548842-82.51086798 68.34111062z" p-id="5406" data-v-c6073ba8></path></svg></div></div></div>
    <script src="/assets/js/app.c7915c77.js" defer></script><script src="/assets/js/3.f80332a6.js" defer></script><script src="/assets/js/1.5cffa4a1.js" defer></script><script src="/assets/js/47.994c7d71.js" defer></script>
  </body>
</html>
